const isConnect = false;
/**
 * 1. 安全限制：小程序只支持wss
 * 2. 长连接限制：小程序后台最长只能保持5分钟
 * 3. 不能超过1MB
 */

/** 创建链接并接收服务器数据
 * 200 连接成功！
 * 201 连接失败！
*/
const _connectAndMsg=(url,callBack)=>{
    const self = this;
    wx.connectSocket({
      url: url,   //服务器WSS地址
      header:{
        'content-type': 'application/json'
      },
    })
    wx.onSocketOpen((res1) => {
        console.log("【info】webSocket连接已开启");
        console.log(res1);
        isConnect = true;
        callBack.call(self,{code:200,msg:'ok'});
        //接受信息
        wx.onSocketMessage((res2) => {
            console.log("【info】接收服务器信息："+res2);
            callBack.call(self,{code:200,body:res2});
        })
    })
    wx.onSocketError((res3) => {
        console.log(res3);
        isConnect = false;
        callBack.call(self,{code:201,msg:'err'});
    })
    wx.onSocketClose(() => {
        isConnect = false;
        console.log("【info】webSocket连接已关闭");
    })
}


/** 向服务器发送数据*/
const _sendSocketMSG=(data)=>{
    //要connectSocket，并在onSocketOpen成功时使用
    if(!isConnect)return;
    wx.sendSocketMessage({
        data: data
    })
}

/** 关闭连接*/
const _closeSocket=()=>{
    //要connectSocket，并在onSocketOpen成功时使用
    if(!isConnect)return;
    wx.closeSocket();
}

//服务器地址
const wssUrl = 'wss://example.com/echo';

module.exports = {
    connect:(callBack)=>_connectAndMsg(wssUrl,callBack),
    sendMsg:(data)=>_sendSocketMSG(data),
    close:()=>_closeSocket(),
}